//
//  SDSendMaViewController.m
//  YYPHSpeedJump
//
//  Created by speedjump on 16/1/3.
//  Copyright © 2016年 sujiang. All rights reserved.
//

#import "SDSendMaViewController.h"
#import "WHC_PhotoListCell.h"
#import "WHC_PictureListVC.h"
#import "WHC_CameraVC.h"
#define kWHC_CellName     (@"WHC_PhotoListCellName")
@interface SDSendMaViewController ()<WHC_ChoicePictureVCDelegate>{
    NSMutableArray  * _imageArr;
    NSString        * _filePath;
    NSString        * _fileName;
    UIView *baseView;
    UIView *photoView;
    UIButton *albumBtn;
}
@property (nonatomic, strong) NSString *token;
@property (nonatomic, strong) NSString *strUrl;

@end

@implementation SDSendMaViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.goodsName.text = [NSString stringWithFormat:@"商品名称: %@", self.name];
    self.priceLable.text = [NSString stringWithFormat:@"购入价: ￥%@",self.price];
    [self.addBtn addTarget:self action:@selector(addBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    self.sdTextView.delegate = self;
  
    [self.addBtn setBackgroundColor:kColors(218, 166, 46, 1)];

    self.title = @"晒!";


}

// 提交
- (IBAction)commitBtn:(id)sender {
    if ([self.sdTextView.text  isEqual: @""]) {
        [Tools showAlert:@"亲,至少说句话呗😊"];
        return;
    } else if (self.image1.image == nil) {
        [Tools showAlert:@"亲,至少晒一张图片哦😜"];
        return;
    } else {
        // /user.do?cmd=make_shaidan&u=x&deal_id=xxx&comment=abcdefg
        NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, @"/user.do?cmd=make_shaidan"];
        NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"deal_id":self.deal_id, @"comment_content":self.sdTextView.text, @"img_url_list":self.strUrl};
        [NetworkHandle getInfoWithUrl:url dictionary:dict success:^(NSDictionary *dictionary) {
           // NSLog(@"%@", dictionary);
          // [Tools showAlert:dictionary[@"message"]];
        }];
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -------------textViewDelegate---------------------
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    UITextRange *selectedRange = [textView markedTextRange];
    
    
    
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    
    if (selectedRange && pos) {
        
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        
        
        if (offsetRange.location < 50) {
            
            return YES;
            
        }
        
        else
            
        {
            return NO;
            
        }
        
    }
    
    
    
    
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    
    
    
    NSInteger caninputlen = 50 - comcatstr.length;
    
    
    
    if (caninputlen >= 0)
        
    {
        
        return YES;
        
    }
    
    else
        
    {
        
        NSInteger len = text.length + caninputlen;
        
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        
        NSRange rg = {0,MAX(len,0)};
        
        
        
        if (rg.length > 0)
            
        {
            
            NSString *s = [text substringWithRange:rg];
            
            
            
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            
            //既然是超出部分截取了，哪一定是最大限制了。
            
            // self.reasonText.text = [NSString stringWithFormat:@"%d/%ld",0,(long)40];
            
        }
        
        return NO;
        
    }
    
    
}
- (void)textViewDidChange:(UITextView *)textView

{
    
    UITextRange *selectedRange = [textView markedTextRange];
    
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    
    
    //如果在变化中是高亮部分在变，就不要计算字符了
    
    if (selectedRange && pos) {
        
        return;
        
    }
    
    
    
    NSString  *nsTextContent = textView.text;
    
    NSInteger existTextNum = nsTextContent.length;
    
    
    if (existTextNum > 50)
        
    {
        //截取到最大位置的字符
        
        NSString *s = [nsTextContent substringToIndex:50];
        
        
        [textView setText:s];
        
    }
    //self.reasonText.text = [NSString stringWithFormat:@"%ld/%d",MAX(0,40- existTextNum),40];
    
}

- (void)addBtnAct:(UIButton *)button
{
    [self.sdTextView endEditing:YES];
    [self.sdTextView resignFirstResponder];

    
    baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    baseView.backgroundColor = [UIColor grayColor];
    baseView.alpha = 0.5;
    [self.view.window addSubview:baseView];
    photoView = [[UIView alloc]initWithFrame:CGRectMake(0, 530*kHeightScale, kScreenWidth, 167*kHeightScale)];
    photoView.backgroundColor = [UIColor whiteColor];
    [self.view.window addSubview:photoView];
    albumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    albumBtn.frame = CGRectMake(14*kWidthScale, 36*kHeightScale, 332*kWidthScale, 32*kHeightScale);
    [albumBtn setTitle:@"从相册中选择" forState:UIControlStateNormal];
    [albumBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [albumBtn addTarget:self action:@selector(albumBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    albumBtn.layer.borderWidth = 1;
    albumBtn.layer.cornerRadius = 5;
    albumBtn.layer.borderColor = kColors(197, 204, 207, 1).CGColor;
    [photoView addSubview:albumBtn];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(14*kWidthScale, 77*kHeightScale, 332*kWidthScale, 32*kHeightScale);
    cancelBtn.layer.cornerRadius = 5;
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.backgroundColor = kColors(218, 166, 46, 1);
    [cancelBtn addTarget:self action:@selector(cancelBtnAct:) forControlEvents:UIControlEventTouchUpInside];
    [photoView addSubview:cancelBtn];

    
}
//从相册中选择

- (void)albumBtnAct:(UIButton *)button
{
    WHC_PictureListVC  * vc = [[WHC_PictureListVC alloc] init];
     
    vc.delegate = self;
    vc.maxChoiceImageNumberumber = 3;
    [self presentViewController:[[UINavigationController alloc]initWithRootViewController:vc] animated:YES completion:nil];
    //[self.navigationController.navigationBar setBackgroundColor:[UIColor blackColor]];
  
    [baseView removeFromSuperview];
    [photoView removeFromSuperview];
    
}
//取消
- (void)cancelBtnAct:(UIButton *)button
{
    [baseView removeFromSuperview];
    [photoView removeFromSuperview];
    

}
- (void)WHCChoicePictureVC:(WHC_ChoicePictureVC *)choicePictureVC didSelectedPhotoArr:(NSArray *)photoArr{
    [NetworkHandle addToWindow];
    
    self.strUrl = nil;
    self.image1.image = nil;
    self.image2.image = nil;
    self.image3.image = nil;
    if (photoArr.count == 1) {
        self.image1.image =photoArr[0];
    }
    if (photoArr.count == 2) {
        self.image1.image = photoArr[0];
        self.image2.image = photoArr[1];
    }
    if (photoArr.count == 3) {
        self.image1.image = photoArr[0];
        self.image2.image = photoArr[1];
        self.image3.image = photoArr[2];
    }
   // NSLog(@"===================%ld", photoArr.count);
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    
    NSString *url =[NSString stringWithFormat:@"%@/app.do?cmd=qn_token",kBaseUrl];
   // NSLog(@"%@",url);
    [NetworkHandle getInfoWithUrl:url dictionary:nil success:^(NSDictionary *dictionary) {
        self.token = dictionary[@"data"];
        for (int i = 0; i < photoArr.count; i++) {
            UIImage *image = photoArr[i];
            NSString *fileName = [NSString stringWithFormat:@"shaidantupian/%@_%d.png", [self getDateTimeString], i];
            NSData *data = [image resizedAndReturnData];
            [upManager putData:data
                           key:fileName
                         token:self.token
                      complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          NSString *tempStr = [NSString stringWithFormat:@"http://7xpm1s.com1.z0.glb.clouddn.com/%@",[resp objectForKey:@"key"]];
                        
                          if (self.strUrl == nil) {
                              self.strUrl = tempStr;
                          } else {
                              self.strUrl = [NSString stringWithFormat:@"%@;%@", self.strUrl, tempStr];
                          }
                          //NSLog(@" --->> Response: %@,  ", [resp objectForKey:@"key"]);
                           NSLog(@"----%@", self.strUrl);
                          [NetworkHandle removeFromWindow];
                } option:nil];
        }
        
    }];
    
    
    
   
}

- (NSString *)getDateTimeString
{
    NSDateFormatter *formatter;
    NSString        *dateString;
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    
    dateString = [formatter stringFromDate:[NSDate date]];
    
    return dateString;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.sdTextView resignFirstResponder];
}

#pragma mark - WHC_CameraVCDelegate
//- (void)WHCCameraVC:(WHC_CameraVC *)cameraVC didSelectedPhoto:(UIImage *)photo{
//    [_imageArr removeAllObjects];
//    [_imageArr addObject:photo];
//    [self WHCChoicePictureVC:nil didSelectedPhotoArr:@[photo]];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
